/**
 * zoneland.net Inc
 * Copyright (c) 2015 
 */
package net.zoneland.zoneapp.common.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 通用的ViewHolder
 * 
 * @author FancyLou
 * @date 2015年4月27日 下午8:33:13
 *
 */
public class ViewHolder {
	/**
	 * listview item 里面的view集合 不是用Map 是因为这个SparseArray效率比较高
	 */
	private SparseArray<View> views;
	@SuppressWarnings("unused")
	private int position;
	private View convertView;

	/**
	 * 
	 */
	public ViewHolder(Context context, ViewGroup parent, int itemLayout,
			int position) {
		this.position = position;
		this.views = new SparseArray<View>();
		this.convertView = LayoutInflater.from(context).inflate(itemLayout,
				parent, false);
		convertView.setTag(this);
	}

	/**
	 * 获取ViewHolder 没有就新建一个
	 * 
	 * @param context
	 * @param convertView
	 * @param parent
	 * @param itemLayout
	 * @param position
	 * @return
	 */
	public static ViewHolder get(Context context, View convertView,
			ViewGroup parent, int itemLayout, int position) {
		if (convertView == null) {
			return new ViewHolder(context, parent, itemLayout, position);
		} else {
			ViewHolder holder = (ViewHolder) convertView.getTag();
			holder.position = position;
			return holder;
		}
	}

	/**
	 * 获取listview item 内的view控件
	 * 
	 * @param viewId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T extends View> T getView(int viewId) {
		View view = views.get(viewId);
		if (view == null) {
			view = convertView.findViewById(viewId);
			views.put(viewId, view);
		}
		return (T) view;
	}

	/**
	 * 给TextView设置显示文本文本
	 * 
	 * @param viewId
	 * @param text
	 * @return
	 */
	public ViewHolder setText(int viewId, String text) {
		TextView view = getView(viewId);
		view.setText(text);
		return this;
	}

	/**
	 * 给图片控件设置resource
	 * 
	 * @param viewId
	 * @param resId
	 * @return
	 */
	public ViewHolder setImageViewResource(int viewId, int resId) {
		ImageView view = getView(viewId);
		view.setImageResource(resId);
		return this;
	}

	/**
	 * 给图片控件设置Bitmap对象
	 * 
	 * @param viewId
	 * @param bitmap
	 * @return
	 */
	public ViewHolder setImageViewBitmap(int viewId, Bitmap bitmap) {
		ImageView view = getView(viewId);
		view.setImageBitmap(bitmap);
		return this;
	}

	/**
	 * @return the convertView
	 */
	public View getConvertView() {
		return convertView;
	}

}
